<template>
  <div class="global-box">
    <div class="title">
      <h1>{{ title }}</h1>
      <a-button type="primary" @click="addCourse('add')">添加课程</a-button>
    </div>
    <a-card :body-style="{ padding: '24px' }" :bordered="false">
      <div class="form-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :md="6" :sm="24">
              <a-form-item label="课程目录">
                <a-cascader
                  :field-names="{ label: 'value', value: 'id', children: 'children' }"
                  change-on-select
                  :options="directoryOptions"
                  :load-data="loadData"
                  placeholder="请选择课程目录"
                  v-model="queryParam.directory"
                  @change="getType"
                />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="课程ID">
                <a-input v-model="queryParam.id" placeholder="" />
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="课程类型">
                <a-select v-model="queryParam.type" placeholder="请选择">
                  <a-select-option
                    :key="item.classTypeId"
                    :value="item.classTypeId"
                    v-for="item in typeList"
                  >
                    {{ item.classTypeName }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="课程属性">
                <a-select v-model="queryParam.attr" placeholder="请选择">
                  <a-select-option :key="item.value" :value="item.value" v-for="item in attrList">{{
                    item.label
                  }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="启用状态">
                <a-select v-model="queryParam.status" placeholder="请选择">
                  <a-select-option :key="item.value" :value="item.value" v-for="item in statusList">
                    {{ item.label }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="18" :sm="24">
              <span class="table-page-search-submitButtons" style="float: right">
                <a-button type="primary" @click="search">筛选</a-button>
                <a-button style="margin-left: 8px" @click="reset">重置</a-button>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <div class="table-wrapper">
        <a-table
          :row-selection="{
            selectedRowKeys: selectedRowKeys,
            onChange: onSelectChange
          }"
          :columns="columns"
          :data-source="data"
          :pagination="pagination"
          :rowKey="record => record.courseId"
        >
          <span slot="action" slot-scope="text, record">
            <template>
              <a @click="handleEdit(record)">编辑</a>
              <a-divider type="vertical" />
              <a @click="handleCopyCourse(record)">复制课程</a>
              <a-divider type="vertical" v-if="record.courseAttributeTypeName === '录播课程'" />
              <a
                @click="handleCopyVideo(record)"
                v-if="record.courseAttributeTypeName === '录播课程'"
              >
                复制课件
              </a>
              <a-divider type="vertical" />
              <a @click="handleLook(record)">查看内容</a>
              <a-divider type="vertical" />
              <a-popconfirm
                placement="top"
                ok-text="确认"
                cancel-text="取消"
                @confirm="handleToggle(record)"
                v-if="record.activeStatus == '启用'"
              >
                <template slot="title">
                  <p>你确定要禁用该课程吗？</p>
                </template>
                <a>禁用</a>
              </a-popconfirm>
              <a @click="handleToggle(record)" v-else>启用</a>
            </template>
          </span>
        </a-table>
        <div class="table-foot" style="margin-top: -47px" v-if="data.length > 0">
          <a-button type="link" @click="showCourseStatusVisible">批量设置课程状态</a-button>
        </div>
      </div>
      <a-modal
        :title="courseStatusTitle"
        :visible="courseStatusVisible"
        :confirm-loading="courseStatusLoading"
        @ok="courseStatusHandleOk"
        @cancel="courseStatusVisible = false"
        okText="提交"
        cancelText="取消"
        width="20%"
      >
        <a-form-model
          ref="ruleForm"
          :model="form"
          :rules="rules"
          :label-col="labelCol"
          :wrapper-col="wrapperCol"
        >
          <a-form-model-item label="批量设置为" prop="courseStatus">
            <a-radio-group v-model="form.courseStatus">
              <a-radio :key="item.value" :value="item.value" v-for="item in formStauts">{{
                item.label
              }}</a-radio>
            </a-radio-group>
          </a-form-model-item>
          <p class="form-status-tip">课程状态影响学员端与后台展示，请谨慎操作！</p>
        </a-form-model>
      </a-modal>
      <view-drawer v-if="courseData.id !== ''" :dataDrawer="courseData" @closeBox="closeBox" />
    </a-card>
  </div>
</template>

<script>
import ViewDrawer from '@/views/product/viewDrawer'
import { directory, type, list, setStatus } from '@/api/product/course'
const columns = [
  {
    title: '课程ID',
    dataIndex: 'courseId',
    align: 'center'
  },
  {
    title: '课程名称',
    dataIndex: 'courseName',
    width: '300px',
    align: 'center'
  },
  {
    title: '课程类型',
    dataIndex: 'courseTypeName',
    align: 'center'
  },
  {
    title: '课程属性',
    dataIndex: 'courseAttributeTypeName',
    align: 'center'
  },
  {
    title: '启用状态',
    dataIndex: 'activeStatus',
    align: 'center'
  },
  {
    title: '排序',
    dataIndex: 'courseOrder',
    align: 'center'
  },
  {
    title: '操作',
    dataIndex: 'action',
    scopedSlots: { customRender: 'action' },
    align: 'center'
  }
]
export default {
  components: {
    ViewDrawer
  },
  data () {
    return {
      title: '课程管理',
      queryParam: {
        directory: [],
        id: '',
        type: undefined,
        attr: undefined,
        status: undefined
      },
      columns,
      data: [],
      selectedRowKeys: [],
      isChecked: false,
      pagination: {
        defaultCurrent: 1, // 默认当前页数
        defaultPageSize: 10, // 默认当前页显示数据的大小
        total: 0, // 总数，必须先有
        showSizeChanger: true,
        showQuickJumper: true,
        onShowSizeChange: (current, pageSize) => {
          this.pagination.defaultCurrent = current
          this.pagination.defaultPageSize = pageSize
          this.getData()
        },
        // 改变每页数量时更新显示
        onChange: (current, size) => {
          this.pagination.defaultCurrent = current
          this.pagination.defaultPageSize = size
          this.getData()
        }
      },
      directoryOptions: [],
      courseStatusVisible: false,
      courseStatusLoading: false,
      courseStatusTitle: '',
      form: {
        courseStatus: 1
      },
      rules: {
        courseStatus: [
          { required: true, message: '请选择状态', trigger: 'change' }
        ]
      },
      formStauts: [{
        label: '启用',
        value: 1
      }, {
        label: '禁用',
        value: 0
      }],
      labelCol: { span: 10 },
      wrapperCol: { span: 14 },
      courseData: {
        visible: false,
        id: ''
      },
      typeList: [],
      attrList: [{
        label: '录播课程',
        value: 1
      }, {
        label: '直播课程',
        value: 2
      }],
      statusList: [{
        label: '启用',
        value: 1
      }, {
        label: '禁用',
        value: 0
      }],
      tableAllSle: [],
      oldExamId: ''
    }
  },
  computed: {
  },
  mounted () {
    this.getDirectory()
    this.getData()
  },
  methods: {
    closeBox (v) {
      this.courseData = {
        visible: false,
        id: ''
      }
    },
    // 获取课程列表数据
    getData () {
      const data = {
        currentPage: this.pagination.defaultCurrent,
        pageSize: this.pagination.defaultPageSize
      }
      if (this.queryParam.status !== '') {
        data.activeStatus = this.queryParam.status
      }
      if (this.queryParam.attr !== '') {
        data.courseAttributeType = this.queryParam.attr
      }
      if (this.queryParam.type !== '') {
        data.courseTypeId = this.queryParam.type
      }
      if (this.queryParam.id !== '') {
        data.courseId = this.queryParam.id
      }
      if (this.queryParam.directory[0]) {
        data.directoryId = this.queryParam.directory[0]
      }
      if (this.queryParam.directory[1]) {
        data.examId = this.queryParam.directory[1]
      }
      if (this.queryParam.directory[2]) {
        data.subjectId = this.queryParam.directory[2]
      }
      if (this.queryParam.directory[3]) {
        data.fourExamId = this.queryParam.directory[3]
      }
      if (this.queryParam.directory[4]) {
        data.fiveExamId = this.queryParam.directory[4]
      }
      if (this.queryParam.directory[5]) {
        data.sixExamId = this.queryParam.directory[5]
      }
      list(data).then(res => {
        if (res.code === '1') {
          this.pagination.total = res.data.totalSize
          this.data = res.data.rows
        } else {
          this.$message.error(res.msg)
        }
      }).catch(err => {
        this.$message.error(err.msg)
      })
    },
    // 添加课程
    addCourse () {
      this.$router.push({
        name: 'productCourseCommon'
      })
    },
    // 表格全选
    onSelectChange (selectedRowKeys, selectedRows) {
      this.tableAllSle = selectedRows
      this.selectedRowKeys = selectedRowKeys
      this.isChecked = this.selectedRowKeys.length === this.data.length
    },
    // 表格全选
    onChangeAll (e) {
      if (e.target.checked) {
        this.isChecked = true
        this.tableAllSle = this.data
        const courseId = this.data.map(item => { return item.courseId })
        const courseIdList = []
        courseIdList.push(courseId)
        this.selectedRowKeys = courseIdList[0]
      } else {
        this.isChecked = false
        this.selectedRowKeys = []
        this.tableAllSle = []
      }
    },
    // 批量设置课程状态
    showCourseStatusVisible () {
      if (this.selectedRowKeys.length > 0) {
        this.courseStatusVisible = true
        this.courseStatusTitle = `批量设置课程状态（已选${this.selectedRowKeys.length}个）`
      } else {
        this.$message.error('请选择课程！')
      }
    },
    // 批量设置课程状态确定
    courseStatusHandleOk () {
      const data = {
        activeStatus: this.form.courseStatus,
        courseIds: this.selectedRowKeys
      }
      setStatus(data).then(res => {
        if (res.code === '1') {
          this.$message.success(res.msg)
          this.getData()
          this.selectedRowKeys = []
        } else {
          this.$message.error(res.msg)
        }
        this.courseStatusVisible = false
      }).catch(err => {
        this.$message.error(err.msg)
      })
    },
    // 表格编辑
    handleEdit (record) {
      this.$router.push({
        name: 'productCourseCommon',
        params: {
          courseId: record.courseId,
          edit: true
        }
      })
    },
    // 表格复制课程
    handleCopyCourse (record) {
      this.$router.push({
        name: 'productCourseCommon',
        params: {
          courseId: record.courseId,
          edit: false
        }
      })
    },
    // 表格复制课件
    handleCopyVideo (record) {
      this.$router.push({
        name: 'productCopyCourse',
        params: {
          courseId: record.courseId
        }
      })
    },
    // 表格查看内容
    handleLook (record) {
      this.courseData.visible = true
      this.courseData.id = record.courseId
    },
    // 表格启用禁用
    handleToggle (record) {
      const data = {
        activeStatus: record.activeStatus !== '启用' ? 1 : 0,
        courseIds: String(record.courseId).split()
      }
      setStatus(data).then(res => {
        if (res.code === '1') {
          this.$message.success(res.msg)
          this.getData()
        } else {
          this.$message.error(res.msg)
        }
      }).catch(err => {
        this.$message.error(err.msg)
      })
    },
    // 筛选
    search () {
      this.getData()
    },
    // 重置
    reset () {
      this.queryParam = {
        directory: [],
        id: '',
        type: undefined,
        attr: undefined,
        status: undefined
      }
      this.selectedRowKeys = []
      this.getData()
    },
    // 获取课程目录
    getDirectory () {
      const data = {
        type: 0,
        directoryLevel: 1
      }
      directory(data).then(res => {
        if (res.code === '1') {
          res.data.forEach(item => {
            item.isLeaf = false
          })
          this.directoryOptions = res.data
        }
      }).catch(err => {
        this.$message.error(err.msg)
      })
    },
    // 课程目录二级-六级
    loadData (selectedOptions) {
      const targetOption = selectedOptions[selectedOptions.length - 1]
      const data = {
        type: 1,
        parentId: targetOption.id,
        directoryLevel: 2
      }
      targetOption.loading = true
      directory(data).then(res => {
        if (res.code === '1') {
          if (res.data.length > 0) {
            res.data.forEach(item => {
              item.isLeaf = false
            })
            targetOption.loading = false
            targetOption.children = [...res.data]
          } else {
            targetOption.loading = false
            this.$message.error('暂无更多数据')
          }
        } else {
          targetOption.loading = false
          this.$message.error(res.msg)
        }
        this.directoryOptions = [...this.directoryOptions]
      }).catch(err => {
        this.$message.error(err.msg)
        targetOption.loading = false
      })
    },
    // 获取课程类型
    getType () {
      if (this.queryParam.directory.length === 0) {
        this.typeList = []
        this.queryParam.type = undefined
      }
      if (!this.queryParam.directory[1]) {
        return false
      }
      if (this.oldExamId === this.queryParam.directory[1]) {
        return false
      }
      const data = {
        examId: this.queryParam.directory[1]
      }
      type(data).then(res => {
        if (res.code === '1') {
          this.typeList = res.data
          this.queryParam.type = undefined
          this.oldExamId = this.queryParam.directory[1]
        } else {
          this.$message.error(res.msg)
        }
      }).catch(err => {
        this.$message.error(err.msg)
      })
    }
  }
}
</script>
<style lang="less" scoped>
.form-status-tip {
  text-align: center;
  color: #999;
}
</style>
